<?php

namespace App\Api\Controllers;

use App\Models\Campus;
use App\Models\Faq;
use App\Models\OrderGoods;
use App\Models\SmsCode;
use App\Models\University;
use App\Models\User;
use Dingo\Api\Http\Request;
use Dingo\Api\Routing\Helpers;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use iscms\Alisms\SendsmsPusher as Sms;



class UserController extends Controller
{
    use Helpers;
    const SmsExpire=1500;//验证码有效期
    /**
     * 名称：个人中心用户信息
     * 必要条件：需要用户认证
     */
    public function index()
    {
        $user=$this->auth->user();
        $user->phone_number=$user->phone_number?:'待完善';
        $user->worth=$this->getWorth();//资产
        $user->nickname=deal_emoji($user->nickname);
        return $this->response()->array([
            'result' => $user,
            'status_code' => 200,
            'message' => '获取用户信息成功'
        ]);
    }



    /**
     * 用户更新字段
     */
    public function updateField(Request $request){
        $allowToUpdata=['name','gender','passowrd','call_phone'];
        $data=$request->input('param');
        if(!in_array($data['field'],$allowToUpdata)){
            return $this->response->array([
                'message'=>'非法请求',
                'status_code'=>500,
            ]);
        }
        $user=$this->auth->user();
        if($data['field']!='password'){
            $user->{$data['field']}=$data['value'];
        }else{
            //密码更新
            if($data['password'] !==$data['confirmPassword']){
                //比对两次确认密码无吴，
                return $this->response->array([
                    'message'=>'密码和确认密码不一致',
                    'status_code'=>500,
                ]);
            }

            //检查原始密码是否正确
            if(!Hash::check($data['oldPassword'], $user->password)){
                return $this->response->array([
                    'message'=>'旧密码输入不正确',
                    'status_code'=>500,
                ]);
            }
            $user->password=bcrypt($data['oldPassword']);
        }

        if($user->save()){
            return $this->response->array([
                'message'=>'更新数据成功',
                'status_code'=>205,
            ]);
        }else{
            return $this->response->array([
                'message'=>'更新数据失败',
                'status_code'=>500,
            ]);
        }

    }


    /**
     * 检测手机号是否被注册
     */
    private function checkPhoneNumber($phoneNumber,$userId){
        $user=User::where([['phone_number','=',$phoneNumber],['id','!=',$userId]])->first();
        return $user?true:false;
    }

    /**
     * @param Request $request
     * @return mixed绑定手机号
     */
    public function bindPhone(Request $request){
        $user=$this->auth->user();
        $data=$request->all();
        //检测手机号
        if($data['phone_number'] && strlen($data['phone_number'])==11){
            //检测验证码
            if(!$this->checkSmsCode($data)){
                return $this->response()->array([
                    "message" => "验证码错误",
                    "status_code" => 201
                ]);
            }
            //检测手机号
            if($this->checkPhoneNumber($data['phone_number'],$user->id)){
                return $this->response()->array([
                    "message" => "手机号已被别人绑定",
                    "status_code" => 201
                ]);
            }

            //更新手机号
            $user->phone_number=$data['phone_number'];
            if(!$user->save()){
                return $this->response()->array([
                    "message" => "绑定失败",
                    "status_code" => 500
                ]);
            }
            if(!$user->university_id){

                return $this->response()->array([
                    "message" => "绑定成功",
                    "status_code" => 410,//需要绑定学校信息
                ]);
            }
            return $this->response()->array([
                "message" => "绑定成功",
                "status_code" => 200
            ]);
        }else{
            return $this->response()->array([
                "message" => "手机号错误",
                "status_code" => 201
            ]);
        }



    }


    /**
     * 保存用户学校，校区信息。不可修改
     */
    public function updateSchoolInfo(Request $request)
    {
        $user=$this->auth->user();
        if($user->university_id){
            return $this->response->array([
                'status_code'=>201,
                'message'=>'学校信息不可修改'
            ]);
        }
        if(!$request->school_id){
            return $this->response->array([
                'status_code'=>201,
                'message'=>'请选择学校'
            ]);
        }
        if(!$request->campus_id){
            return $this->response->array([
                'status_code'=>201,
                'message'=>'请选择校区'
            ]);
        }

        $user->university_id=$request->school_id;
        $user->campus_id=$request->campus_id;
        //更新用户地址，便于显示
        $user->address=University::where('id',$user->university_id)->value('name').Campus::where('id',$user->campus_id)->value('name');
        if($user->save()){
            return $this->response->array([
                'status_code'=>200,
                'message'=>'更新成功'
            ]);
        }else{
            return $this->response->array([
                'status_code'=>201,
                'message'=>'更新失败'
            ]);
        }

    }
    /**
     * 我的客户，展示对方已成功付费的订单，
     * 只能查询到客户已支付或已完成的订单
     */
    public function customer(){
        $user=$this->auth->user();
        //return $user->id;
        $orderUserList=DB::table('order_user as ou')
            ->leftJoin('order as o','ou.order_id','=','o.id')
            ->leftJoin('users as u','ou.user_id','=','u.id')
            ->where([['ou.contact_user_id',$user->id],['o.order_status',1]])
            ->select('ou.confirm_status','ou.send_money','ou.contact_user_id','ou.id','ou.order_id','u.head_img','u.nickname','u.gender','u.address','u.phone_number')
            ->get();
        if(count($orderUserList)==0){
            return $this->response->array([
                'status_code'=>200,
                'message'=>'没有数据'
            ]);
        }
        foreach ($orderUserList as $v){
            $v->totalMoney=0;
            $v->nickname=deal_emoji($v->nickname);
            $v->goodsList=OrderGoods::where('order_user_id',$v->id)->get();
            foreach ($v->goodsList as $v1){
                $v->totalMoney+=$v1->contact_user_price;
            }
        }

        return $this->response->array([
            'status_code'=>200,
            'message'=>'获取数据成功',
            'result'=>$orderUserList
        ]);

    }
    //统计用户资产
    public function getWorth()
    {
        $user=$this->auth->user();
        $worth=DB::table('depot as d')
            ->leftJoin('goods as g','d.goods_id','=','g.id')
            ->where('user_id',$user->id)
            ->select(DB::raw("sum(d.total*g.price*g.discount/100) as worth"))
            ->first();
        return $worth->worth?:0;
    }
    //客服中心
    public function faq()
    {
        $data=Faq::where('is_show',1)->orderBy('sort')->get();
        return $this->response->array([
            'status_code'=>200,
            'message'=>'获取数据成功',
            'result'=>$data
        ]);
    }
    /**
     * @return bool
     * 检查短信验证码
     */
    public function checkSmsCode($data){
        if(strlen($data['phone_number'])==11 && strlen($data['sms_code'])>=4){
            $code=SmsCode::where([['phone_number',$data['phone_number']],['code',$data['sms_code']],['ctime','>',time()-self::SmsExpire],['status',0]])->first();
            if($code){
                $code->status=1;
                $code->save();
                return true;
            }
            return false;
        }else{
            return false;
        }
        return true;
    }
}